<template>
  <div>
    <el-select v-model="localData.pageId" placeholder="请选择页面" filterable clearable @change="handlePageAndTypeChange(true)">
      <el-option v-for="page in pageOptions" :key="page.pageId" :label="page.pageName" :value="page.pageId"> </el-option>
    </el-select>
    <el-select v-model="localData.type" placeholder="请选择类型" filterable clearable @change="handlePageAndTypeChange(true)">
      <el-option v-for="type in typeOptions" :label="type.label" :value="type.value" :key="type.value" />
    </el-select>
    <el-cascader
      :props="CascaderProps"
      :options="compOptions"
      v-model="localData.component"
      placeholder="请选择组件"
      filterable
      clearable
      :show-all-levels="false"
      @change="handleCompChange(true)"
      style="width: 100%"
    >
    </el-cascader>
    <el-select filterable clearable v-model="localData.event" placeholder="请选择方法">
      <el-option v-for="(event, idx) in eventOptions" :key="idx" :label="event.label" :value="event.value"> </el-option>
    </el-select>
    <el-input v-model="localData.jsonPath" placeholder="请输入jsonPath" />
  </div>
</template>

<script>
import { searchFormByPageId, searchPages } from '@code/components/anvil-code-low-common/api/page';
import formEvents from '@code/components/anvil-code-low-common/utils/formEvents';
import fieldMethods from '@code/components/anvil-code-low-common/components/exportFieldMethods';
import { Base64 } from 'js-base64';
import { isBase64 } from '@/utils/zmids'

export default {
  name: 'CompCallItem',
  props: {
    modelValue: {
      type: Object,
      default: () => {}
    },
    fields: {
      type: Array,
      default: () => []
    },
    options: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      localData: {},
      pageOptions: [],
      typeOptions: [
        {
          label: '表单',
          value: 'form'
        },
        {
          label: '组件',
          value: 'component'
        }
      ],
      compOptions: [],
      eventOptions: [],
      CascaderProps: {
        value: 'uuid',
        label: 'fieldName',
        children: 'children',
        checkStrictly: true,
        emitPath: false
      }
    };
  },
  watch: {
    modelValue: {
      handler(newVal) {
        this.localData = newVal;
      },
      immediate: true,
      deep: true
    },
    localData: {
      handler(newVal) {
        this.$emit('update:modelValue', newVal);
      },

      deep: true
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      await this.searchPageList();
      await this.handlePageAndTypeChange();
      this.handleCompChange();
    },
    async searchPageList() {
      return searchPages().then((res) => {
        // 找到当前页面,放置到列表首条并添加标识
        const { getPageId } = this.useAnvilCodeStore();
        let idx = 0;
        this.pageOptions = res.data.map((item, index) => {
          if (item.pageId == getPageId) {
            idx = index;
            item.pageName = '当前页面' + `(${item.pageName})`;
          }
          return item;
        });
        this.pageOptions.unshift(this.pageOptions.splice(idx, 1)[0]);
      });
    },
    // 获取当前页面内组件列表
    async getPageFields(pageId, isForm = false) {
      return searchFormByPageId(pageId).then((res) => {
        if(!res){
          return []
        }
        let { pageFormJson } = res.data
        if(isBase64(pageFormJson)){
          pageFormJson = Base64.decode(pageFormJson)
        }
        const formOption = JSON.parse(pageFormJson);
        if (isForm) {
          return formOption;
        } else {
          const list = this.getJsonCallableCompList(formOption);
          return list;
        }
      });
    },
    async getCompOptions(pageId, type) {
      const { getPageId } = this.useAnvilCodeStore();
      if (type == 'form') {
        const options = pageId == getPageId ? this.options : await this.getPageFields(pageId, true);
        return [
          {
            fieldName: '当前表单',
            uuid: pageId,
            options
          }
        ];
      } else {
        const curFields = pageId == getPageId ? this.fields : await this.getPageFields(pageId);
        const curCasaFields = this.getCasaFields(curFields);
        console.log('当前级联', curCasaFields);
        return curCasaFields;
      }
    },
    getEventOptions(type, uuid, fields) {
      if (type == 'form') {
        // 找到pageId对应的表单并在原本方法的基础上添加自定义函数
        const { funcs } = fields[0].options;
        if (funcs && funcs.length) {
          const list = funcs.map((f) => {
            return {
              label: f.funcLabel,
              value: f.funcName
            };
          });
          return [...formEvents, ...list];
        } else {
          return formEvents;
        }
      } else {
        // 寻找树节点
        const findNode = (tree, predicate) => {
          for (const node of tree) {
            if (predicate(node)) {
              return node;
            }
            if (node.children) {
              const found = findNode(node.children, predicate);
              if (found) {
                return found;
              }
            }
          }
          return null;
        };

        const field = findNode(fields, (f) => f.uuid == uuid);

        fields.find((f) => f.uuid == uuid);
        if (field) {
          const methodItem = fieldMethods.find((item) => item.type == field.type);
          const methodsArr = methodItem ? methodItem.methods : [];
          const funcArr = field.funcs ? field.funcs : [];
          const resArr = [
            ...methodsArr,
            ...funcArr.map((f) => {
              return {
                label: f.funcLabel,
                value: f.funcName
              };
            })
          ];
          return resArr;
        }
      }
    },
    // 获取级联组件列表
    getCasaFields(fields) {
      return fields
        .map((f) => {
          const { type, fieldName } = f;
          // 处理聚合类型的组件
          if (type == 'customButtonGroup') {
            const children = f.btnGroup.map((btn) => {
              return {
                ...btn,
                fieldName: btn.buttonName
              };
            });
            return {
              ...f,
              children
            };
          } else {
            return {
              ...f,
              fieldName: f.fieldName ? f.fieldName : f.label ? f.label : '未命名组件',
              children: f.children && f.children.column ? f.children.column : []
            };
          }
        })
        .filter((f) => f.uuid);
    },
    async handlePageAndTypeChange(isClear) {
      if (this.localData.pageId && this.localData.type) {
        this.compOptions = await this.getCompOptions(this.localData.pageId, this.localData.type);
      }
      // 是否重置component和event字段
      if (isClear) {
        this.localData.component = '';
        this.localData.event = '';
      }
    },
    handleCompChange(isClearEvent) {
      this.eventOptions = this.getEventOptions(this.localData.type, this.localData.component, this.compOptions);
      // 是否重置event字段
      if (isClearEvent) {
        this.localData.event = '';
      }
    }
  }
};
</script>